package com.health.system.security.handle;

import com.health.system.common.result.Result;
import com.health.system.common.utils.JsonUtil;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录成功处理器
 *
 */
public class BlogAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    private final SessionRegistry sessionRegistry;
    public BlogAuthenticationSuccessHandler(SessionRegistry sessionRegistry) {
        this.sessionRegistry = sessionRegistry;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        // 登录成功, 将其注册到session表中
        sessionRegistry.registerNewSession(request.getSession(true).getId(), authentication.getPrincipal());

        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpStatus.OK.value());
        String result = JsonUtil.writer(Result.ok("登录成功"));
        response.getWriter().write(result);
    }

}
